<script setup lang="ts">
import { useElementSize, useEventListener } from '@vueuse/core';
import { AxesHelper, Vector3, Box3, Group, PerspectiveCamera, Scene, WebGLRenderer } from 'three'
import { watch, onBeforeUnmount, reactive, unref, onMounted, ref } from 'vue';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls.js'
import { RandomObjs } from '../models'

const scene = new Scene()
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 5000)

// RandomObjs.position.set(300, 0, 0)
// camera.lookAt(boxmesh.position)
// scene.add(boxmesh)
const group = new Group()
RandomObjs.forEach(v => {
  group.add(v)
})

scene.add(group)

const box = new Box3()
box.setFromObject(group)
const center = new Vector3()
box.getCenter(center)
group.position.sub(center)
const viewEleRef = ref<HTMLElement>(), canvasEle = ref<HTMLCanvasElement>()
const containerSizeInfo = reactive(useElementSize(viewEleRef))

let renderer: WebGLRenderer
// camera.position.set(23000, 23000, 23000)
camera.position.set(200, 200, 200)
watch(containerSizeInfo, (v) => {
  renderer.setSize(v.width, v.height)
  camera.aspect = v.width / v.height
  camera.updateProjectionMatrix()
})
function Render() {
  renderer.render(scene, camera)
  requestAnimationFrame(Render)
}
const axesIn = new AxesHelper(300)

function Strat(params: any) {
  console.log(params.target);

  console.time('orbit操作');
}
function end(params: any) {
  console.log(params.target);

  console.timeEnd('orbit操作');
}
function change() {
  console.timeLog('orbit操作')
}
let Trackball: TrackballControls
onMounted(() => {

  // console.time('计时开始');
  renderer = new WebGLRenderer({ canvas: unref(canvasEle)! })
  Trackball = new TrackballControls(camera, renderer.domElement)
  Trackball.rotateSpeed = 1
  Trackball.zoomSpeed = 1.2
  Trackball.panSpeed = 0.8
  Trackball.addEventListener('start', Strat)
  Trackball.addEventListener('end', end)
  Trackball.addEventListener('change', change)
  scene.add(axesIn)

  Render()
})

onBeforeUnmount(() => {
  renderer.dispose()
  // console.timeEnd('计时开始');
  Trackball.removeEventListener('start', Strat)
  Trackball.removeEventListener('end', end)
})
const xRota = ref<HTMLInputElement>()
useEventListener<InputEvent>(xRota, 'input', (e) => {

  group.rotateX(Number.parseFloat(e.target.value))
})
</script>

<template>
  <main ref="viewEleRef">
    <div>
      <form>
        <label>
          x旋转角度
          <input ref="xRota" type="range" :max="Math.PI * 2" :step="0.00001" />
        </label>
      </form>
    </div>
    <canvas :width="containerSizeInfo.width" :height="containerSizeInfo.height" ref="canvasEle"></canvas>
  </main>
</template>
<style>
main {
  height: 100%;
}
</style>